package com.ukao.steward.dialog;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.BaseDialogFragment;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.widget.StateButton;
import com.ukao.steward.widget.StateImageView;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;

import static com.ukao.steward.R.id.sure_btn;
import static com.ukao.steward.R.id.txt_error;
import static com.ukao.steward.R.id.txt_trans_no;
import static com.ukao.steward.consts.Constant.TAG_NO;
import static com.ukao.steward.consts.Constant.TRANS_NO;

/**
 * 添加运单号
 */
public class TransNoDialogFragment extends BaseDialogFragment {


    @BindView(R.id.close_btn)
    ImageView closeBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.trans_no_layout)
    RelativeLayout transNoLayout;
    @BindView(R.id.edit_text)
    EditText editText;
    @BindView(R.id.sweep_btn)
    StateImageView sweepBtn;
    @BindView(txt_error)
    TextView txtError;
    @BindView(sure_btn)
    StateButton sureBtn;
    @BindView(R.id.trans_no_succeed)
    LinearLayout transNoSucceed;
    @BindView(txt_trans_no)
    TextView txtTransNo;
    @BindView(R.id.trans_no_succeed_layout)
    LinearLayout transNoSucceedLayout;
    Unbinder unbinder;
    private String mParam1;
    private String mParam2;

    private String error;
    private String mTitle;
    private String editTextHide;
    private boolean isAddTransNo;
    private  String  orderId;
    private  String  userRemark;
    private  String  bindCode;
    private  String  clothingId;



    public static TransNoDialogFragment newInstance(String error,String mTitle,String editTextHide,
                                                    boolean isAddTransNo ,String orderId, String userRemark,String  bindCode,String  clothingId) {
        TransNoDialogFragment fragment = new TransNoDialogFragment();
        Bundle args = new Bundle();
        args.putString("error", error);
        args.putString("mTitle", mTitle);
        args.putString("orderId", orderId);
        args.putString("editTextHide", editTextHide);
        args.putBoolean("isAddTransNo", isAddTransNo);
        args.putString("userRemark", userRemark);
        args.putString("bindCode", bindCode);
        args.putString("clothingId", clothingId);
        fragment.setArguments(args);
        return fragment;
    }




    @Override
    protected void initView() {
        title.setText(mTitle);
        editText.setHint(editTextHide);
        setShowBottom(true);
        setIsWithWrap(false);
    }

    @Override
    protected void initListener() {
        super.initListener();
        editText.addTextChangedListener(new MyTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (s.toString().isEmpty()){
                    txtError.setText("");
                }
            }
        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {

                    submitRequest();
                    return  true;
                }

                return false;
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId= getArguments().getString("orderId");
            userRemark= getArguments().getString("userRemark");
            error= getArguments().getString("error");
            mTitle= getArguments().getString("mTitle");
            editTextHide= getArguments().getString("editTextHide");
            isAddTransNo= getArguments().getBoolean("isAddTransNo",false);
            bindCode= getArguments().getString("bindCode");
            clothingId= getArguments().getString("clothingId");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_trans_no_dialog, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.close_btn, R.id.sweep_btn, sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_btn:
                dismiss();
                break;
            case R.id.sweep_btn:
                Intent mIntent = ActivityUtils.JumpToBundleActivity(activity);
                startActivityForResult(mIntent ,Constant.REQUEST_CODE);
                break;
            case sure_btn:
                submitRequest();

                break;
        }
    }

    void submitRequest() {
        String streditText = getText(editText);
        if (CheckUtils.isEmpty(streditText)) {

            return ;
        }
        if (!getText(sureBtn).equals("确定")) {

        return ;
          }

        addTransNo(streditText);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == activity.RESULT_OK) {

            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String  code=data.getStringExtra(Constant.ARG_PARAM1);
                    editText.setText(code);
                    break;
            }
        }

    }






    /**
     * 添加运单号
     *
     *
     * @param transNo 运单号
     */
    public void addTransNo(final String transNo ) {
        KeyBoardUtil.hideInputmethod(editText);
        sureBtn.setText("添加中");
        HashMap mHashMap = new HashMap<String, String>();
        Observable mObservable=null;
        if (isAddTransNo){
            mHashMap.put("orderId",orderId);
            mHashMap.put("transNo",transNo);
            if (!CheckUtils.isEmpty(userRemark)) mHashMap.put("userRemark", userRemark);
            mHashMap.put("accessToken", SaveParams.getToken());
            mObservable = apiStores().addtransNo(Constant.createParameter(mHashMap));
        }else{
            mHashMap.put("id",clothingId);
            mHashMap.put("bindCode",transNo);
            mHashMap.put("accessToken", SaveParams.getToken());
            mObservable = apiStores().bindCode(Constant.createParameter(mHashMap));
        }


        addSubscription(mObservable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {

                        if (model.getHttpCode() == 200) {
                            if (mDialogSubmitListener!=null){
                                mDialogSubmitListener.onSubmitClick(isAddTransNo?TRANS_NO:TAG_NO,transNo);
                            }
                            transNoSucceedLayout.setVisibility(View.VISIBLE);
                            transNoSucceed.setVisibility(View.GONE);
                            txtTransNo.setText(error+transNo);
                            txtError.setText("");
                        }else  if (model.getHttpCode() == 400){
                            transNoSucceedLayout.setVisibility(View.GONE);
                            transNoSucceed.setVisibility(View.VISIBLE);
                            txtError.setText(model.getMsg());


                        }

                    }


                    @Override
                    public void onFinish() {
                        sureBtn.setText("确定");

                    }
                });

    }

    public static Builder createBuilder(
            FragmentManager fragmentManager) {
        return new Builder(fragmentManager);
    }

    public static final class Builder {
        private String error="运单号：";
        private String mTitle="录运单号";
        private String editTextHide="请输入运单号";
        private boolean isAddTransNo=true;
        private  String  orderId;
        private  String  userRemark;
        private  String  bindCode;
        private  String  clothingId;
        private DialogSubmitListener mListener;
        private   FragmentManager  mFragmentManager;

        public   Builder(FragmentManager fragmentManager){
            mFragmentManager=fragmentManager;
        }

        private Builder(Builder builder) {
            orderId = builder.orderId;
            userRemark = builder.userRemark;
            bindCode = builder.bindCode;
            clothingId = builder.clothingId;
        }

        public Builder orderId(String val) {
            orderId = val;
            return this;
        }

        public Builder userRemark(String val) {
            userRemark = val;
            return this;
        }

        public Builder bindCode(String val) {
            bindCode = val;
            return this;
        }

        public Builder clothingId(String val) {
            clothingId = val;
            return this;
        }
        public Builder error(String val) {
            error = val;
            return this;
        }

        public Builder mTitle(String val) {
            mTitle = val;
            return this;
        }

        public Builder EditTextHide(String val) {
            editTextHide = val;
            return this;
        }

        public Builder isAddTransNo(boolean val) {
            isAddTransNo = val;
            return this;
        }

        public Builder mListener(DialogSubmitListener val) {
            mListener = val;
            return this;
        }




        public  TransNoDialogFragment  show(){
            TransNoDialogFragment mUnTakeDialog =TransNoDialogFragment.newInstance(  error, mTitle, editTextHide,
             isAddTransNo , orderId,  userRemark,  bindCode,  clothingId);
            mUnTakeDialog.setOnSubmitClickListener(mListener);
            mUnTakeDialog.show(mFragmentManager,TransNoDialogFragment.class.getName());
            return   mUnTakeDialog;

        };




    }
}
